import { useRef, useState } from "react";
import "./App.css";
import Controller from "./utils/controller";

function App() {
  const gridSize = useRef(null)
  const movement = useRef(null)
  const [controller, setController] = useState(null)
  const [inputRole, setInputRole] = useState(null)
  const [submitted, setSubmitted] = useState(false)
  const [zomb, setZomb] = useState(false)
  const zombPos = useRef(null)
  const inputCreaturePos = useRef([])
  const generateGrid = () => {
    const target = gridSize.current.value
    if (Number(target).toString() === 'NaN' || target <= 0) {
      alert("请输入一个大于0的数字作为网格尺寸")
      return
    }
    setController(new Controller(target))
    const emptyArr = []
    for (let i = 0; i < target; i++) {
      emptyArr.push(new Array())
      for (let j = 0; j < target; j++) {
        emptyArr[i].push(-1)
      }
    }
    setInputRole(emptyArr)
  }
  const addRole = (row, col) => {
    setInputRole((state) => {
      const target = [...state.map((val) => [...val])]
      controller.addRole(col, row)
      if (zomb === false) {
        target[row][col] = 1
        zombPos.current = {
          x: col,
          y: row
        }
        setZomb(true)
      } else {
        inputCreaturePos.current.push({
          x: col,
          y: row
        })
        target[row][col] = 0
      }
      return target
    })
  }
  const submit = () => {
    const target = movement.current.value
    const movements = target.match(/[RLUDrlud]/g)
    if (movements.length === 0) {
      alert("没有检测到有效的动作，请输入R/L/U/D")
      return
    }
    controller.setInitialMovement(movements)
    controller.execute()
    setSubmitted(true)
    // 获取input output
    const input = {
      gridSize: gridSize.current.value,
      zombie: zombPos.current,
      creatures: inputCreaturePos.current,
      commands: movement.current.value.match(/[RLUDrlud]/g).join("").toUpperCase()
    }
    const output = {
      zombies: [...controller.zombies.values()].map((item) => ({ x: item.x, y: item.y })),
      creatures: [...controller.creatures.values()].map((item) => ({ x: item.x, y: item.y }))
    }
    console.log(JSON.stringify(input))
    console.log(JSON.stringify(output))
  }
  return (
    <div className="container">
      <div className="sidebar">
        <div className="item">
          <div className="item-title">1. 生成网格</div>
          <div className="item-content">
            <div>网格容量(NxN)</div>
            <input ref={gridSize} disabled={controller} placeholder="输入一个整数" min={0} className="flex" type="text"/>
          </div>
          <button onClick={generateGrid} disabled={controller}>生成</button>
        </div>
        <div className="item">
          <div className="item-title">2. 点击网格生成僵尸</div>
          <div className="item-content">首次点击为僵尸</div>
        </div>
        <div className="item">
          <div className="item-title">3. 点击网格生成生物</div>
          <div className="item-content">从第二次点击开始生成生物</div>
        </div>
        <div className="item">
          <div className="item-title">4. 输入丧尸移动方式</div>
          <div className="item-content">
            <input ref={movement} disabled={submitted} className="flex" placeholder="U上D下L左R右 如：RDRU" type="text"/>
          </div>
        </div>
        <div className="item">
          <div className="item-title">5. 执行操作</div>
          <div className="item-content">
            <button onClick={submit} disabled={submitted}>submit</button>
          </div>
        </div>
      </div>
      <div id="content">
        {
          inputRole && !submitted ? (
            inputRole.map((row, rowId) => (
              <div className="row" key={rowId}>
                {
                  row.map((item, colId) => (
                    <div className="disp-item" key={colId} onClick={() => {addRole(rowId, colId)}}>
                      {
                        item === 1 ? 'X' : item === 0 ? 'O' : ''
                      }
                    </div>
                  ))
                }
              </div>
            ))
          ) : null
        }
        {
          controller && submitted ? (
            controller.data.map((row, rowId) =>
              <div className="row" key={rowId}>
                {
                  row.map((item, colId) => (
                    <div className="disp-item result" key={colId}>
                      {
                        item.length > 0 ? item[0].type === 1 ? 'X' : item[0].type === 0 ? 'O' : ''
                          : null
                      }
                    </div>
                  ))
                }
              </div>
            )
          ) : null
        }
      </div>
    </div>
  );
}

export default App;
